from django.http import *
from django.forms import ModelForm
from django.contrib.auth import logout
from django.template import *
from django.shortcuts import *
from django.template.loader import get_template
from l2ldjango.apps.usermanagement.forms import *
from django.core.mail import send_mail
from l2ldjango.apps.usermanagement.models import *
from django.contrib.auth import authenticate, login
from django.middleware import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import get_hexdigest, check_password
import random
import string
from django.utils import simplejson
from django.core import serializers
#import json
from django.conf import settings
from l2ldjango.apps.firm.views import *
from django.contrib.auth.models import User
from l2ldjango.apps.personalblog.models import *
from l2ldjango.apps.firm.models import *
from django.core.mail import EmailMessage
from l2ldjango.apps.citystate.models import *
from l2ldjango.apps.lawschool.models import *
from l2ldjango.apps.lawschool.views import *
from l2ldjango.apps.referral.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.paginator import InvalidPage, EmptyPage
from django.db.models import Q
from l2ldjango.apps.jobsapp.models import *
from l2ldjango.settings import DATABASES
from l2ldjango.apps.usermanagement import uuid 
from django.template import RequestContext
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from paypal.standard.forms import PayPalPaymentsForm
from django.contrib import messages

from django.template.loader import render_to_string
from django.utils.html import strip_tags

#from django.contrib.sessions.models import Session
from django.http import HttpResponse, iri_to_uri
class HttpResponseTemporaryRedirect(HttpResponse):
    status_code = 307
    def __init__(self, redirect_to):
        HttpResponse.__init__(self)
        self['Location'] = iri_to_uri(redirect_to)

from django.core.mail import (
    EmailMultiAlternatives,
)

def local_redirect(request,path=""):
    #A local redirect for the yucky /l2l/ prefix while developing
    if request.GET.has_key('term'):
        path = '%s?term=%s' % (path,request.GET['term'])
    return HttpResponseTemporaryRedirect('/'+path)

def runquery(qry):
    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost",DATABASES['default']['USER'],DATABASES['default']['PASSWORD'],DATABASES['default']['NAME'] )
    
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    
    # execute SQL query using execute() method.
    cursor.execute(qry)
    
    # Fetch a single row using fetchone() method.
    #data = cursor.fetchone()
    
    #print "Database version : %s " % data
    
    # disconnect from server
    db.close()


def getAdminEmail():
	usr=User.objects.get(pk=1)
	return usr.email

def firstName(request):
	usr=User.objects.all()
	#try:
	for u in usr:
		u.first_name=u.first_name.lstrip('0123456789 ')
		u.save()
	#except:
		#return HttpResponse('Data Update Failed')
	return HttpResponse('Data Update Success')
	
def getMemberFirmsOf(userid):
      firms=FirmGroup.objects.filter(member=userid)
      return firms


#for ajax autocomplete in searchbox
import simplejson
def getAttorneys(request):
	term=request.GET['term'].lower()
	#attorneys=userprofile.objects.filter(user_type=1,visible_in_search=1)
	#a=[]
	#if attorneys:
			#for aid in attorneys:
				#a.append(aid.user.id)
	#model_results=User.objects.filter(username__icontains=term,is_active=1,pk__in=a)[:10]
	model_results=User.objects.filter(username__icontains=term,is_active=1)[:10]
	results = [ x.username for x in model_results ]
	#data = serializers.serialize('json', results, fields=('username','first_name','last_name'))
	jsondata = simplejson.dumps(results)
	return HttpResponse(jsondata, mimetype='application/json')

def getMyFriends(request):
	term=request.GET['term'].lower()
	friends=Friends.objects.filter(
								Q(status="APPROVED"),
								Q(initiator=request.user.id)| Q(receiver=request.user.id))
	f=[]
	if friends:
			for fid in friends:
				f.append(fid.receiver.id)
				
	model_results=User.objects.filter(username__icontains=term,is_active=1,pk__in=f)[:10]
	results = [ x.username for x in model_results ]
	#data = serializers.serialize('json', results, fields=('username','first_name','last_name'))
	jsondata = simplejson.dumps(results)
	return HttpResponse(jsondata, mimetype='application/json')


def getStudents(request):
	term=request.GET['term'].lower()
	students=userprofile.objects.filter(user_type=2,visible_in_search=1)
	s=[]
	if students:
			for sid in students:
				s.append(sid.user.id)
				
	model_results=User.objects.filter(username__icontains=term,is_active=1,pk__in=s)[:10]
	results = [ x.username for x in model_results ]
	#data = serializers.serialize('json', results, fields=('username','first_name','last_name'))
	jsondata = simplejson.dumps(results)
	return HttpResponse(jsondata, mimetype='application/json')

def getUsers(request):
	term=request.GET['term'].lower()
	model_results=User.objects.filter(username__icontains=term,is_active=1)[:20]
	results = [ x.username for x in model_results ]
	#data = serializers.serialize('json', results, fields=('username','first_name','last_name'))
	jsondata = simplejson.dumps(results)
	return HttpResponse(jsondata, mimetype='application/json')


@login_required
def sendReferralForm(request,referee_id):
	referee=User.objects.get(pk=referee_id)
	variables=RequestContext(request,{'referee':referee,'title':'Referral Form'})
	return render_to_response('user/send_referral.html',variables )
	

@login_required
def sendReferral(request):
	referee_id=request.POST['referee']	
	referee=User.objects.get(pk=referee_id)
	refered_by=request.user
	refered_to_username=request.POST['refer_to']
	#return HttpResponse(refered_to_id)
	refered_to=User.objects.get(username=refered_to_username)
	try:
		r=Referrals.objects.get(refered_by=refered_by,refered_to=refered_to,referee=referee)
		message='%s%s%s%s'%(referee.username,' is already referred to ',refered_to.username,'.')
		title="Referral already sent"
			
	except ObjectDoesNotExist:	
		if referee==refered_to:
			title="Sending Failure"
			message='%s%s'%(referee.username,' cannot be referred to himself.')
		elif referee==request.user:
			title="Cannot refer yourself"
			message='Your reference has to be sent by others.'
		elif refered_to==request.user:
			title="Cannot refer to yourself"
			message='Others can send reference to you,You cannot send referral to yourself.'
		else:
			#send message 
			#email=refered_to.email
			email="mahesh@wework4web.com"
			addlink='%s%s%s'%('<a href="http://destructible.me/l2l/users/view-profile/',referee.id,'">View Profile</a>')
			email_message='%s%s%s%s%s'%(refered_by.username,' has referred attorney <strong>',referee.username,'</strong>.<br/>click the link below to know about him.<br/>',addlink)
			msg=EmailMessage('L2L Attorney Referral',email_message,'no-reply@lawyertolawyerny.com',[email])
			msg.content_subtype="html"
			msg.send()
			#save referrals info in db
			r=Referrals()
			r.refered_to=refered_to
			r.refered_by=refered_by
			r.referee=referee
			r.save()
			message="Referral Successfully Sent."
			title="Success Message"
	#return viewMyFriends(request,message=message,title=title)	
	return HttpResponse('%s%s%s'%(title,'-',message))
	     
def home_page(request):
    blogs=PersonalBlog.objects.filter(status=3).order_by("-creation_date")
    variables = RequestContext(request,{'user':request.user,'blogs':blogs}) 
    return render_to_response('pages/home.html',variables )	
    #if request.user.id:
    #    return showDashboard(request)
    #else:
    #    return render_to_response('pages/home.html',variables )	
	
def searchAttorney(request):
	search_attorney=request.POST["searchtext"]	
	rawqry='%s%s%s%s%s%s%s'%('select a.* from usermanagement_userprofile a,auth_user b where a.user_id=b.id and (b.username like "%%',search_attorney,'%%" or b.first_name like "%%',search_attorney,'%%" or b.last_name like"%%',search_attorney,'%%")and a.user_type=1 and b.is_active=1 and a.visible_in_search=1')
	#return HttpResponse(rawqry)
	#rawqry='select * from usermanagement_userprofile where user_id<100'
	results=userprofile.objects.raw(rawqry)
	try:
		frnd_list=Friends.objects.filter(initiator=request.user)
		f=[]
		if frnd_list:
			for ff in frnd_list:
				f.append(ff.receiver.id)
	except:
		f=[]
	variables=RequestContext(request,{'frnd_list':f,'title':'Search Results','attorneys':results,'searchtxt':search_attorney})
	return render_to_response('user/attorney_search.html',variables )
	
def searchStudDirectory(request):
	search_attorney=request.POST["searchtext"]	
	rawqry='%s%s%s%s%s%s%s'%('select a.* from usermanagement_userprofile a,auth_user b where a.user_id=b.id and (b.username like "%%',search_attorney,'%%" or b.first_name like "%%',search_attorney,'%%" or b.last_name like"%%',search_attorney,'%%")and a.user_type=2 and b.is_active=1 and a.visible_in_search=1')
	#return HttpResponse(rawqry)
	#rawqry='select * from usermanagement_userprofile where user_id<100'
	results=userprofile.objects.raw(rawqry)
	try:
		frnd_list=Friends.objects.filter(initiator=request.user)
		f=[]
		if frnd_list:
			for ff in frnd_list:
				f.append(ff.receiver.id)
	except:
		f=[]
	variables=RequestContext(request,{'frnd_list':f,'title':'Search Results','attorneys':results,'searchtxt':search_attorney})
	return render_to_response('user/student_search.html',variables )	

def searchFriend(request):
	try:
		usr = User.objects.get(username=request.POST["searchfriends"])
		userid = [x.id for x in usr]
		frnd = Friends.objects.get(initiator=request.user.id,receiver__in=userid,status='APPROVED')			
		usr_images = ImageGallery.objects.filter(user__in=userid)
		len_images = len(list(usr_images))
		images = ImageGallery.objects.all()
		imgId = []					
		imgId = [ x.user for x in images ]
	except:
		usr = []
		frnd = []
	title = 'Search result for "%s"'%(request.POST["searchfriends"])
	message = ''
	len_usr = len(list(usr))	
	variables = RequestContext(request,{'usr':usr,'frnd':frnd,'title':title,'message':message,'len_usr':len_usr,'images':images,'imgId':imgId})	
	return render_to_response('user/friend_by_search.html',variables)
	
def searchStudent(request):
	search_attorney=request.POST["searchtext-all"]
	rawqry='%s%s%s%s%s%s%s'%('select a.* from usermanagement_userprofile a,auth_user b where a.user_id=b.id and a.user_type=2 and (b.username like "%%',search_attorney,'%%" or b.first_name like "%%',search_attorney,'%%" or b.last_name like"%%',search_attorney,'%%")and  b.is_active=1 and a.visible_in_search=1')
	#rawqry='select * from usermanagement_userprofile where user_id<100'
	results=userprofile.objects.raw(rawqry)
	try:
		frnd_list=Friends.objects.filter(initiator=request.user)
		f=[]
		if frnd_list:
			for ff in frnd_list:
				f.append(ff.receiver.id)
	except:
		f=[]
	variables=RequestContext(request,{'frnd_list':f,'title':'Search Results','attorneys':results,'searchtxt':search_attorney})
	return render_to_response('user/all_search.html',variables )		
   	#return HttpResponse(rawqry)	

def searchAll(request):
	search_attorney=request.POST["searchtext-all"]
	rawqry='%s%s%s%s%s%s%s'%('select a.* from usermanagement_userprofile a,auth_user b where a.user_id=b.id and (b.username like "%%',search_attorney,'%%" or b.first_name like "%%',search_attorney,'%%" or b.last_name like"%%',search_attorney,'%%")and  b.is_active=1 and a.visible_in_search=1')
	#rawqry='select * from usermanagement_userprofile where user_id<100'
	results=userprofile.objects.raw(rawqry)
	try:
		frnd_list=Friends.objects.filter(initiator=request.user)
		f=[]
		if frnd_list:
			for ff in frnd_list:
				f.append(ff.receiver.id)
	except:
		f=[]
	variables=RequestContext(request,{'frnd_list':f,'title':'Search Results','attorneys':results,'searchtxt':search_attorney})
	return render_to_response('user/all_search.html',variables )		
   	#return HttpResponse(rawqry)	
   	
   	
def searchAttorney11(request):
	from l2ldjango.apps.lawschool.models import *
	rr='select * from lawschool_lawschool'
	r=lawschool.objects.raw(rr)
	variables=RequestContext(request,{'attorneys':r})
	return render_to_response('user/attorney_search.html',variables )	
   	#return HttpResponse(r)	
   	
def sendVerification(request):	
	#licenceno=request.POST['licence'];
	licenceno='1000025'
	try:
		from django.core import serializers
		usrprofile=userprofile.objects.get(licence=licenceno,old_imported=1);
		#usrprofile=serialize('json',usrprofile)
		response={'licence_exists':True,'userinfo':usrprofile};
	except ObjectDoesNotExist:	
		response={'licence_exists':False};
	#response=serialize('json', response)
	#jsondata = json.dumps({"c": 0, "b": 0, "a": 0}) 
	#sondata=json.dumps(response)   
	response= Session.objects.aggregate(Max('date'), Min('date'))
 
	return HttpResponse(simplejson.dumps(simplejson.loads(serialize('json', response,ensure_ascii=False)))
)

def successfully_registered(request):
    variables = RequestContext(request,{'title':'Success!','message':'You have been registered. You will be notified after an administrator activates your account.'})
    return render_to_response('pages/success_page.html',variables)

def register_page_attorney(request):
    form = ShortRegistrationForm()
    if request.POST:
        form = ShortRegistrationForm(request.POST)
        if form.is_valid():
            
            new_user = User.objects.create_user(form.cleaned_data['email'], 
                                                form.cleaned_data['email'], 
                                                form.cleaned_data['password1'])
            new_user.is_active = False
            new_user.groups.add(1)
            new_user.save()
            
            profile_with_license,created_profile = userprofile.objects.get_or_create(licence=form.cleaned_data['license_number'],
                                                                                     full_name__iexact=('%s' % form.cleaned_data['full_name']))
            profile_with_license.full_name = form.cleaned_data['full_name']
            profile_with_license.email = form.cleaned_data['email']
            profile_with_license.user=new_user
            profile_with_license.user_type=1
            profile_with_license.first_time=True
            profile_with_license.save()
            
            #Send the user an email
            to = [form.cleaned_data['email']]
            from_email = 'no-reply@lawyertolawyerny.com'
            
            html_content = render_to_string('email_templates/registration_success.html', {'user':new_user})
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives('Successfully registered for L2L!', text_content, from_email, to)
            msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)
            
            #Send the admin an email
            if settings.IS_LOCAL:
                to = ['chris.cohoat@gmail.com']
                from_email = 'chris.cohoat@gmail.com'
            else:
                to = ['chris.cohoat@gmail.com','james@destructible.me']
                from_email = 'no-reply@lawyertolawyerny.com'
            
            html_content = render_to_string('email_templates/alert_admin_of_registration.html', {'user':new_user})
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives('A new user has registed for L2L.com', text_content, from_email, to)
            msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)
            
            return HttpResponseRedirect('success/')
            
    return render_to_response('user/attorney_registration.html',{'form':form},context_instance=RequestContext(request))

'''
def register_page_attorney(request):
	state=zipcode.objects.all()
	if request.method == 'POST':
		#username=request.POST['username']
		username=request.POST['email']
		password=request.POST['password']
		#email=request.POST['email']
		email=request.POST['email'] #request.POST['username']
		licence=request.POST['licence']
		#validate username existence
		existing_username=User.objects.filter(username=username)
		if len(existing_username)>0:
			title="Username already exists"
			message="Please try to Register with other Username."
			variables = RequestContext(request,{'title':title,'message':message})
			return render_to_response('pages/success_page.html',variables)
			#return render_to_response('user/myprofile.html',variables)
		else:
			#validate email existence
			existing_email=User.objects.filter(email=email)
			if len(existing_email)>0:
				title="Email already exists"
				message="Please try to Register with other Email Address."
				variables = RequestContext(request,{'title':title,'message':message})
				return render_to_response('pages/success_page.html',variables)

			else:
				#continue validating licence
				existing_user_licence=userprofile.objects.filter(licence=licence)
				if len(existing_user_licence)>0:
					if len(existing_user_licence)==1:
						existing_user=userprofile.objects.get(licence=licence)
						if existing_user.old_imported==1:
							#register and activate,send email
							user=existing_user.user
							user.email=email
							user.username=username
							#changing password
							user.set_password(password)
							#user.save()
							user.is_active=True
							#user.groups.clear()
							user.save()
							user.groups.add(1) # add by id(Attorney)
							user.save()
							#update child table
							existing_user.user_type=1
							existing_user.verified=True
							existing_user.first_time=True
							existing_user.save()
							#sending email to the user
							email=email
							addlink='<a href="http://destructible.me/l2l/users/login/">Login From Here</a>'
							email_message='%s%s%s%s%s%s'%('You have been Successfully registered to L2L.Your Old Account has been activated.<br/>username:',username,'<br/>password:',password,'<br/>click here to Login<br/>',addlink)
							msg=EmailMessage('L2L Attroney Registration',email_message,'no-reply@lawyertolawyerny.com',[email])
							msg.content_subtype="html"
							msg.send(fail_silently=True)
							#sending email to the Admin
							email_admin=getAdminEmail()
							addlink='<a href="http://destructible.me/l2l/users/login/">Login From Here</a>'
							email_message='%s%s%s%s%s%s%s%s%s%s'%('User ',username ,'has Registered with existing Licence number ',licence,' and is already active.<br/>username:',username,'<br/>licence:',licence,'<br/>Email:',email)
							msg=EmailMessage('L2L Attroney Registration',email_message,email,[email_admin])
							msg.content_subtype="html"
							msg.send(fail_silently=True)
							title="Licence already exists"
							message="Your Existing account has been activated.Please Check your Email."
							variables = RequestContext(request,{'title':title,'message':message})
							return render_to_response('pages/success_page.html',variables)
							#return render_to_response('user/myprofile.html',variables)
						else:
							#register new user,inactive and waiting for Admin approval						
							usr = User.objects.create_user(username=username,password=password,email=email)
							usr.is_active=False
							usertype=1
							usr.groups.add(usertype) # add by id(Attorney)
							usr.save()
							#saving data in child table of user
							usrpf=userprofile()
							usrpf.user=usr
							usrpf.user_type=1
							usrpf.first_time=True
							usrpf.licence=licence
							usrpf.save()
							title="Registration Succeeded!!"
							message="You are successfully registered with existing Licence,But you cannot login until Admin verifies Your Account.Thank you."
							variables = RequestContext(request,{'title':title,'message':message})
							#email='themaheshe1@gmail.com'
							#send email to the registered user
							email=usr.email
							userinfos='%s%s%s%s'%('Username:',usr.username,'<br/>password:',password)
							email_message='%s%s'%('You have been Successfully registered to L2L.Your can login only after L2L Admin verifies your account.You will soon receive activation notice from L2l Admin.<br/>Your Login info:<br/>',userinfos)
							msg=EmailMessage('L2L Registration',email_message,'no-reply@lawyertolawyerny.com',[email])
							msg.content_subtype="html"
							msg.send(fail_silently=True)
							#send email to the admin
							email_admin=getAdminEmail()
							userinfos='%s%s%s%s%s%s'%('Username:',usr.username,'<br/>Email:',usr.email,'<br/>Licence:',licence)
							activate_link='%s%s%s'%('<br/><a href="http://destructible.me/l2l/users/enable/',usr.id,'">Click here to Enable this user</a>')
							email_message='%s%s%s'%('New user has been registered to L2L with a licence which already exists.<br/>',userinfos,activate_link)
							msg=EmailMessage('L2L Attorney Registration with duplicate licence',email_message,email,[email_admin])
							msg.content_subtype="html"
							msg.send(fail_silently=True)						
							return render_to_response('pages/success_page.html',variables)
					
					
					else:
						#register new user,inactive and waiting for Admin approval						
						usr = User.objects.create_user(username=username,password=password,email=email)
						usr.is_active=False
						usertype=1
						usr.groups.add(usertype) # add by id(Attorney)
						usr.save()
						#saving data in child table of user
						usrpf=userprofile()
						usrpf.user=usr
						usrpf.user_type=1
						usrpf.first_time=True
						usrpf.licence=licence
						usrpf.save()
						title="Registration Succeeded!!"
						message="You are successfully registered with existing Licence,But you cannot login until Admin verifies Your Account.Thank you."
						variables = RequestContext(request,{'title':title,'message':message})
						#email='themaheshe1@gmail.com'
						#send email to the registered user
						email=usr.email
						userinfos='%s%s%s%s'%('Username:',usr.username,'<br/>password:',password)
						email_message='%s%s'%('You have been Successfully registered to L2L.Your can login only after L2L Admin verifies your account.You will soon receive activation notice from L2l Admin.<br/>Your Login info:<br/>',userinfos)
						msg=EmailMessage('L2L Registration',email_message,'no-reply@lawyertolawyerny.com',[email])
						msg.content_subtype="html"
						msg.send(fail_silently=True)
						#send email to the admin
						email_admin=getAdminEmail()
						userinfos='%s%s%s%s%s%s'%('Username:',usr.username,'<br/>Email:',usr.email,'<br/>Licence:',licence)
						activate_link='%s%s%s'%('<br/><a href="http://destructible.me/l2l/users/enable/',usr.id,'">Click here to Enable this user</a>')
						email_message='%s%s%s'%('New user has been registered to L2L with a licence which already exists.<br/>',userinfos,activate_link)
						msg=EmailMessage('L2L Attorney Registration with duplicate licence',email_message,email,[email_admin])
						msg.content_subtype="html"
						msg.send(fail_silently=True)						
						return render_to_response('pages/success_page.html',variables)
						
				else:
					usr = User.objects.create_user(username=username,password=password,email=email)
					usr.is_active=False
					usertype=1
					usr.groups.add(usertype) # add by id(Attorney)
					usr.save()
					#saving data in child table of user
					usrpf=userprofile()
					usrpf.user=usr
					usrpf.user_type=1
					usrpf.first_time=True
					usrpf.licence=licence
					usrpf.save()
					title="Registration Succeeded!!"
					message="You are successfully registered,But you cannot login until Admin verifies Your Account.Thank you."
					variables = RequestContext(request,{'title':title,'message':message})
					#email='themaheshe1@gmail.com'
					#send email to the registered user
					email=usr.email
					userinfos='%s%s%s%s'%('Username:',usr.username,'<br/>password:',password)
					email_message='%s%s'%('You have been Successfully registered to L2L.Your can login only after L2L Admin verifies your account.You will soon receive activation notice from L2l Admin.<br/>Your Login info:<br/>',userinfos)
					msg=EmailMessage('L2L Registration',email_message,'no-reply@lawyertolawyerny.com',[email])
					msg.content_subtype="html"
					#try:
					msg.send(fail_silently=True)
					#except:
					#	print "ERROR"
					#send email to the admin
					email_admin=getAdminEmail()
					userinfos='%s%s%s%s%s%s'%('Username:',usr.username,'<br/>Email:',usr.email,'<br/>Licence:',licence)
					activate_link='%s%s%s'%('<br/><a href="http://destructible.me/l2l/users/enable/',usr.id,'">Click here to Enable this user</a>')
					email_message='%s%s%s'%('New user has been registered to L2L.<br/>',userinfos,activate_link)
					msg=EmailMessage('L2L Attorney Registration',email_message,'no-reply@lawyertolawyerny.com',[email_admin])
					msg.content_subtype="html"
					#try:
					msg.send(fail_silently=True)
					#except:
					#	print "ERROR !"
					return render_to_response('pages/success_page.html',variables)
		
	
	else:
		title="User Registration"
		message=""
		variables = RequestContext(request,{'state':state,'message':message,'title':title})
		return render_to_response('user/attorney_registration.html',variables)   
'''

def validateUsernameDoesnotExist(request):
	try:
		usr = User.objects.get(username=request.POST["mail_to"])
		return HttpResponse("true") 
	except:
		try:
			usr = User.objects.get(username=request.POST["refer_to"])
			return HttpResponse("true") 
		except:
			return HttpResponse("false")

def validateEmailDoesnotExist(request):
	try:
		usr = User.objects.get(email=request.POST["email"])
		return HttpResponse("true") 
	except:
		return HttpResponse("false")
	
#validation for username existence while creating user
def validateUsernameExistence(request,edit=""):
    try:
        usr = User.objects.get(username=request.POST["username"]) 
        if edit:
			if usr.username==request.user.username:
				   return HttpResponse("true")
			else:
				return HttpResponse("false")
        else:
         return HttpResponse("false")
    except:
        return HttpResponse("true")


#validation for username existence while creating user
def validateUsernameExistence_new(request,edit=""):
    usr = User.objects.filter(username=request.POST["username"]) 
    if len(usr)>0:
    	if edit:
			if usr.username==request.user.username:
				   return HttpResponse("true")
			else:
				return HttpResponse("false")
        else:
         return HttpResponse("false")
    else:
    	return HttpResponse("true")    
      
#validation for email existence while creating user
def validateEmailExistence_new(request,edit=""):
    usr = User.objects.filter(email=request.POST["email"]) 
    if len(usr)>0:
    	if edit:
			if usr.email==request.user.email:
				   return HttpResponse("true")
			else:
				return HttpResponse("false")
        else:
         return HttpResponse("false")
    else:
    	return HttpResponse("true")


def validateEmailExistence(request,edit=""):
    try:
    	usr = User.objects.get(email=request.POST["email"]) 
    
    	if edit:
			if usr.email==request.user.email:
				   return HttpResponse("true")
			else:
				return HttpResponse("false")
        else:
         return HttpResponse("false")
    except:
    	return HttpResponse("true")  

def checkSchool(email):
    emailaddress=email;
    incoming_domain=email.index('@')+1
    domain_name=emailaddress[incoming_domain:]    
    lawschools=lawschool.objects.all();
    addressvalid=False;
    for ls in lawschools:
        if ls.example_email==domain_name:
            addressvalid=True
            
    return addressvalid
	       
def validateEmailExistenceStudent(request):
    try:
		usr = User.objects.get(email=request.POST["email"]) 
		return HttpResponse("false")        
    except:
		if checkSchool(request.POST["email"]):
			return HttpResponse("true")
		else:
			return HttpResponse("false")
          

#validation for username existence while creating user
def validateUsernameExistenceEdit(request):
    try:
		usr = User.objects.get(username=request.POST["username"])
		if usr.username==request.user.username:
			return HttpResponse("true")
		else:
			return HttpResponse("false")
		#return HttpResponse("false")
    except:
        return HttpResponse("true")
       
#validation for email existence while creating user
def validateEmailExistenceEdit(request):
    try:
		usr = User.objects.get(email=request.POST["email"])  
		if usr.email==request.user.email:
			return HttpResponse("true")
		else:
			return HttpResponse("false")
    except:
        return HttpResponse("true")

def validateZipExistence(request):
	try:
		zip_code = zipcode.objects.get(zip=request.POST["zip"])  
		return HttpResponse("true")
	except:
	    return HttpResponse("false")
#Admin enables user when he gets message after registration process.admin gets the enable link in email

@login_required
def enableUser(request,userid):
	usr=User.objects.get(pk=userid)
	if request.user.id==1:
		usr.is_active=True
		usr.save()
		usrprofile=userprofile.objects.get(user=usr.id)
		usrprofile.verified=True
		usrprofile.save()
		#send message to the user about his account activation
		email=usr.email
		email_message='Your Account has been Successfully Activated. You can now login with your login details.'
		msg=EmailMessage('Account Activated,L2l',email_message,'no-reply@lawyertolawyerny.com',[email])
		msg.content_subtype="html"
		msg.send()
		message="User activated successfully."
		title="Activation Succeeded"
		variables = RequestContext(request,{'message':message,'title':title})
		return render_to_response('pages/success_page.html',variables)  
	else:
		message="You Dont have any permissions to Activate users."
		title="Permission Denied"
		variables = RequestContext(request,{'message':message,'title':title})
		return render_to_response('pages/success_page.html',variables)  

#attorney directory page
def lawyerDirectory(request):
	if 'state' in request.GET and 'prarea' in request.GET and 'searchtxt' in request.GET:
		attorneys = filterLawyerDirectory(request,request.GET["state"],request.GET["prarea"],request.GET["searchtxt"])
		state = request.GET["state"]		
		prarea	= request.GET["prarea"]
		searchtxt = request.GET["searchtxt"]
		title=""
		message=""
		pracareas = PracticeArea.objects.all()
		qry = "select id,state from citystate_zipcode group by state"
		states = zipcode.objects.raw(qry)
		#states = zipcode.objects.order_by('state').distinct('state')
		variables = RequestContext(request,{'attorneys':attorneys,'title':title,'message':message,'pracareas':pracareas,'states':states,'state':state,'prarea':prarea,'searchtxt':searchtxt})	
		return render_to_response('user/lawyer_directory.html',variables)
		
	else:
		#rawqry='select a.* from usermanagement_userprofile,auth_user b where a.user_id=b.id and b.is_active=1'
		#usrs=User.objects.filter(is_active=1)[:10]
		#usrs_list=[ x.id for x in usrs]
		#results=userprofile.objects.filter(user__in=usrs_list)
		results=userprofile.objects.filter(visible_in_search=1)
		#results=userprofile.objects.raw(rawqry)
		paginator = Paginator(results, 10) # Show 15 Users per page
		try:
			page = int(request.GET.get('page', '1'))
		except ValueError:
			page = 1
		try:
			attorneys = paginator.page(page)
		except (EmptyPage, InvalidPage):
			attorneys = paginator.page(paginator.num_pages)	
		
		title=""
		message=""
		pracareas = PracticeArea.objects.all()
		qry = "select id,state from citystate_zipcode group by state"
		states = zipcode.objects.raw(qry)
		#states = zipcode.objects.order_by('state').distinct('state')
		variables = RequestContext(request,{'attorneys':attorneys,'title':title,'message':message,'pracareas':pracareas,'states':states})	
		return render_to_response('user/lawyer_directory.html',variables)
	
def filterLawyerDirectory(request,state='',prarea='',searchtxt=''):	
	#rawqry='select a.* from usermanagement_userprofile,auth_user b where a.user_id=b.id and b.is_active=1'
	#usrs=User.objects.filter(is_active=1)[:10]
	#usrs_list=[ x.id for x in usrs]
	#results=userprofile.objects.filter(user__in=usrs_list)
	if request.method == 'POST':
		searchtxt = request.POST["search"]
		prarea = request.POST["practiceareas"]
		state = request.POST["state"]		
	if searchtxt != 'search...' or searchtxt != '':
		usr = User.objects.filter(username__icontains=searchtxt)
		usrs_list=[ x.id for x in usr]	
	
	if (searchtxt == 'search...' or searchtxt == '') and prarea == '-1' and state == '-1':
		#current search		
		results=userprofile.objects.filter(visible_in_search=1)
	
	elif (searchtxt == 'search...' or searchtxt == '') and prarea == '-1' and state != '-1':			
		#search by zipcode
		results=userprofile.objects.filter(state=state)
	
	elif (searchtxt == 'search...' or searchtxt == '') and prarea != '-1' and state == '-1':			
		#search by practice areas
		results=userprofile.objects.filter(primary_area = prarea)
	
	elif (searchtxt == 'search...' or searchtxt == '') and prarea != '-1' and state != '-1':			
		#search by practice areas and zip code
		results=userprofile.objects.filter(primary_area = prarea,state=state)	
	
	elif (searchtxt != 'search...' or searchtxt != '') and prarea == '-1' and state == '-1':			
		#search by search only		
		results=userprofile.objects.filter(user__in=usrs_list)
		
	elif (searchtxt != 'search...' or searchtxt != '') and prarea == '-1' and state != '-1':			
		#search by search, zipcode		
		results=userprofile.objects.filter(user__in=usrs_list,state=state)
	
	elif (searchtxt != 'search...' or searchtxt != '') and prarea != '-1' and state == '-1':			
		#search by search, practice areas
		results=userprofile.objects.filter(user__in=usrs_list,primary_area = prarea)
	
	else:
		#search by search, practice areas and zipcode
		results=userprofile.objects.filter(user__in=usrs_list,primary_area = prarea,state=state)
		
	paginator = Paginator(results, 10) # Show 15 Users per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		attorneys = paginator.page(page)
	except (EmptyPage, InvalidPage):
		attorneys = paginator.page(paginator.num_pages)	
	
	if request.method == 'POST':
		title=""
		message=""
		pracareas = PracticeArea.objects.all()
		qry = "select id,state from citystate_zipcode group by state"
		states = zipcode.objects.raw(qry)
		#states = zipcode.objects.order_by('state').distinct('state')
		variables = RequestContext(request,{'attorneys':attorneys,'title':title,'message':message,'pracareas':pracareas,'states':states})	
		return render_to_response('user/filter_lawyer_directory.html',variables)
	else:
		return attorneys


def lawStudents(request):
    #rawqry='select a.* from usermanagement_userprofile,auth_user b where a.user_id=b.id and b.is_active=1'
    usrs=User.objects.filter(is_active=1)[:10]
    usrs_list=[ x.id for x in usrs]
    #results=userprofile.objects.filter(user__in=usrs_list)
    results=userprofile.objects.filter(user_type=2,visible_in_search=1)
    
    #results=userprofile.objects.raw(rawqry)
    paginator = Paginator(results, 10) # Show 15 Users per page
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        students = paginator.page(page)
    except (EmptyPage, InvalidPage):
        students = paginator.page(paginator.num_pages)    
    
    title=""
    message=""
    variables = RequestContext(request,{'students':students,'title':title,'message':message})    
    return render_to_response('user/law_students.html',variables) 
	
def register_page_student(request):
	if request.method == 'POST':
		username=request.POST['username']
		password=request.POST['password']
		email=request.POST['email']
	
		try:
			existing_username=User.objects.get(username=username)				
			title="Username already exists"
			message="You cannot use the username which is already used by others.Try again with another username."
			variables = RequestContext(request,{'title':title,'message':message})
			return render_to_response('user/student_registration.html',variables)
		except ObjectDoesNotExist:		
			try:
				existing_email=User.objects.get(email=email)
				title="Email already exists"
				message="You cannot use the Email which is used by others.Try again with another Email."
				variables = RequestContext(request,{'title':title,'message':message})
				return render_to_response('user/student_registration.html',variables)
			except:
				usr = User.objects.create_user(username=username,password=password,email=email)
				usr.is_active=False
				usertype=2
				usr.groups.add(usertype) # add by id(Attorney)
				usr.save()
				#saving data in child table of user
				usrpf=userprofile()
				usrpf.user=usr
				usrpf.user_type=2
				usrpf.first_time=True
				usrpf.save()
				title="Registration Succeeded!!"
				message="You are successfully registered,But you cannot login until Admin verifies Your Account.Thank you."
				variables = RequestContext(request,{'title':title,'message':message})
				#email='themaheshe1@gmail.com'
				#send email to the registered user
				email=usr.email
				userinfos='%s%s%s%s'%('Username:',usr.username,'<br/>password:',password)
				email_message='%s%s'%('You have been Successfully registered to L2L.Your can login only after L2L Admin verifies your account.You will soon receive activation notice from L2l Admin.<br/>Your Login info:<br/>',userinfos)
				msg=EmailMessage('L2L Registration',email_message,'no-reply@lawyertolawyerny.com',[email])
				msg.content_subtype="html"
				msg.send()
				#send email to the admin
				email_admin=getAdminEmail()
				school=getLawschoolByEmail(usr.email)
				userinfos='%s%s%s%s%s%s'%('Username:',usr.username,'<br/>Email:',usr.email,'<br/>Law School:',school)
				activate_link='%s%s%s'%('<br/><a href="http://destructible.me/l2l/users/enable/',usr.id,'">Click here to Enable this user</a>')
				email_message='%s%s%s'%('New user has been registered to L2L.<br/>',userinfos,activate_link)
				msg=EmailMessage('L2L Student Registration',email_message,'no-reply@lawyertolawyerny.com',[email_admin])
				msg.content_subtype="html"
				msg.send()
				return render_to_response('pages/success_page.html',variables)
	
	else:
		title="User Registration"
		message=""
		variables = RequestContext(request,{'message':message,'title':title})
		return render_to_response('user/student_registration.html',variables)  


def addImages(request):
	if request.method == 'POST':
		a="images"
	else:
		title="Your Photos"
		message="Add Your Photos"
		variables = RequestContext(request,{'message':message,'title':title})
		return render_to_response('user/addimages.html',variables)  

		 
def register_page(request):
	if request.method == 'POST':
		form1 = UserProfileForm(request.POST)
		form2 = RegistrationForm(request.POST)
		
		if form1.is_valid() and form2.is_valid():
			#saving user in auth_user table
			#try:
				
				#usr = User.objects.create_user(username=form2.cleaned_data['username'],password=request.POST['password'],email=form2.cleaned_data['email'])
				usr = User.objects.create_user(username=form2.cleaned_data['email'],password=request.POST['password'],email=form2.cleaned_data['username'])
				usr.first_name=form2.cleaned_data['first_name']
				usr.last_name=form2.cleaned_data['last_name']
				usr.is_active=False
				#usertype=form1.cleaned_data['user_type']
				#usr.groups.add(usertype) # add by id(Attorney)
				usr.save()
				#form1.user=usr.id
				usrpf=form1.save()
				#form1.cleaned_data['user']=usr			
				#return HttpResponse(form1.user)
				usrprofile=userprofile.objects.get(pk=usrpf.id)
				usrprofile.user=usr
				usrprofile.verification_code=getRamdomCode(999999999)
				usrprofile.save()
				title="Registration Succeeded!!"
				message="You are successfully registered,Please Verify Your account from your email to complete registration.Thank you"
				variables = RequestContext(request,{'title':title,'message':message})
				#email='themaheshe1@gmail.com'
				email=usr.username
				addlink='%s%s%s'%('<a href="http://destructible.me/l2l/users/verification/',usrprofile.verification_code,'">Verify Your L2L Account,click here.</a>')
				email_message='%s%s'%('You have been Successfully registered to L2L.com.Please click link below to verify Your account.<br/>',addlink)
				print email_message
				
				#try:
					#msg=EmailMessage('L2L Registration',email_message,'no-reply@lawyertolawyerny.com',['sunilpatelmca1810@gmail.com'])
					
				#m = EmailMultiAlternatives(
			    #    	subject="Someone you invited signed up for WonderHop",
				#		body="invite_accepted_email.txt",
			    #    	from_email="WonderHop <contact@wonderhop.com>", 
			    #    	to=[email],
        		#	)
				#m.attach_alternative("invite_accepted_email.html", "text/html")
				#try:
				#	m.send()
				#except Exception, e:
					#logging.exception("Exception sending referred-user email")
				#	print "######################",e
                
					#msg=EmailMessage('L2L Registration',email_message,'sunilpatelmca1810@gmail.com',['sunilpatelmca1810@gmail.com'])
					#msg.content_subtype="html"
					#msg.send()
				#except Exception, e:
				#	print e
				#email_message='%s%s'%('You have been Successfully registered to L2L.com.Please click link below to verify Your account',addlink)
				#send_mail('L2L Registration',email_message, 'no-reply@lawyertolawyerny.com',[email], fail_silently=False)
				return render_to_response('user/attorney_registration.html',variables)
				
			#except:
				#title="Registration Failed,couldnot save!!"
				#message="Try again!!"	
				#variables = RequestContext(request,{'form1': form1,'form2':form2,'title':title,'message':message})
				#return render_to_response('user/registration.html',variables)
		else:
			errs1=form1.errors
			errs2=form2.errors
			errs='%s%s'%(errs1,errs2)
			#form = RegistrationForm()
			variables = RequestContext(request,{'form1': form1,'form2':form2,'message':errs})
			return render_to_response('user/registration.html',variables)	
	else:
		form2 = RegistrationForm()
		form1 =  UserProfileForm()
		variables = RequestContext(request,{'form1': form1,'form2':form2,'message':'Fill up this registration form'})
		return render_to_response('user/registration.html',variables)


def userVerification(request,verificationCode):
	#try:
	usrprofile=userprofile.objects.get(verification_code=verificationCode)
	usrprofile.verified=1
	usrprofile.save()
	user=User.objects.get(pk=int(usrprofile.user.id))
	user.is_active=True
	user.save()
	message="User Successfully Verified.Welcome to L2L"
	user = User.objects.get(pk=usrprofile.user.id,is_active=True)
	user.backend = 'django.contrib.auth.backends.ModelBackend'
	login(request,user)	
	variables = RequestContext(request,{'message':message,'user': user,'title':'Dashboard'} )
	#except:
		#message="Verification Failed!!"	
	#return render_to_response('pages/home.html',variables)	
	
	return render_to_response('user/dashboard.html',variables)  

def getRamdomCode(code_range):
	return random.randrange(code_range)

def register_page1(request):
	if request.method == 'POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			#saving user in auth_user table
			user = User.objects.create_user(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],email=form.cleaned_data['email'])
			usertype=form.cleaned_data['user_type']
			user.groups.add(usertype) # add by id(Attorney)
			user.first_name=form.cleaned_data['first_name']
			user.last_name=form.cleaned_data['last_name']
			email=user.email			
			user.save()
			#saving user profile details in child-table
			licence=form.cleaned_data['licence']
			phone=form.cleaned_data['phone']
			address=form.cleaned_data['address']
			city=form.cleaned_data['city']
			target_graduation_date=form.cleaned_data['graduation_date']
			visible_in_search=form.cleaned_data['Visible_in_search']		
			user_type=form.cleaned_data['user_type']
			dat= userprofile(licence=licence,user_type=user_type,phone=phone,address=address,city=city,target_graduation_date=target_graduation_date,visible_in_search=visible_in_search,user=user)
			dat.save()
			#send_mail('L2L Registration','You have been Successfully registered to L2L.com', 'no-reply@lawyertolawyerny.com',[email], fail_silently=False)
			#send_mail('Successfully registered to Windtrader', 'User registered',user.username,['themaheshe1@gmail.com'])
			#return render_to_response('main_page.html',{ 'user': request.user } )
			variables = RequestContext(request,{'title':'Registration Succeeded!!','message':'You are successfully registered,Thank you'})
			return render_to_response('pages/success_page.html',variables)
		else:
			errs=form.errors
			form = RegistrationForm()
			variables = RequestContext(request,{'form': form,'message':errs})
			return render_to_response('user/registration.html',variables)	
	else:
		form = RegistrationForm()
		variables = RequestContext(request,{'form': form,'message':'Fill up this registration form'})
		return render_to_response('user/registration.html',variables)	


def register_facebook(request):
	if request.method=='POST':
		fb_id 	    = request.POST["id"]
		username	= request.POST["username"]
		firstname	= request.POST["firstname"]
		lastname	= request.POST["lastname"]
		email		= request.POST["email"]		
		
		N=12
		#fb_id= '100001778104032'
		#username='blow_flower2001@yahoo.com'
		#firstname='rojina'
		#lastname='karki'
		#email='blow_flower2001@yahoo.com'
		
		password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
		request.session["fb_user_passsword"] = password
		request.session["fb_user_email"] = email
					
		try:
			user = User.objects.get(email = email,is_active=True)
			user.backend = 'django.contrib.auth.backends.ModelBackend'
			login(request,user)
			
			
			return HttpResponse('/l2l/users/dashboard/')

		except ObjectDoesNotExist:
			try:
				user = User.objects.get(email = email)
				request.session["message"] = "Account already exists and is inactive. Verify via email."
				return HttpResponse('/l2l/')
			except:
				if 'fb_user' in request.session:
				#if request.session["fb_user"]:
					#del request.session["fb_user"]
					form1 =  UserProfileForm()
					variables = RequestContext(request,{'form1': form1,'message':'Required for Registration'})
					#return render_to_response('user/fb_registration.html',variables)
					return HttpResponse('/l2l/users/fbsave/')
				else:
					user = User.objects.create_user(username=email,password=password,email=email)
					user.first_name=firstname
					user.last_name=lastname
					user.is_active=False
					#usertype=form1.cleaned_data['user_type']
					#user.groups.add(usertype) # add by id(Attorney)
					user.save()		
					request.session["fb_user"] = user.id				
					#form2 = RegistrationForm()
					form1 =  UserProfileForm()
					form1.user=user
					variables = RequestContext(request,{'form1': form1,'message':'Required for Registration'})
					#return render_to_response('user/fb_registration.html',variables)
					return HttpResponse('/l2l/users/fbsave/')
			
					
				
				
def saveFbAddtionalInfo(request):
	if request.method == 'POST':
		form1 = UserProfileForm(request.POST)	
		
		if form1.is_valid() :
			#saving user in auth_user table
			#try:	
				usr=User.objects.get(email=request.session["fb_user_email"])
				usr.is_active=True
				usertype=form1.cleaned_data['user_type']
				usr.groups.add(usertype) # add by id(Attorney)
				usr.save()
				
				usrpf=form1.save()
				usrprofile=userprofile.objects.get(pk=usrpf.id)
				usrprofile.user=usr
				usrprofile.verified=1
				usrprofile.address2=request.session["fb_user_passsword"]
				usrprofile.save()
				password=request.session["fb_user_passsword"]
				email=request.session["fb_user_email"]
				#email='themaheshe1@gmail.com'
				#sending login credentials to the user
				try:
					emailmsg = "Your registration details from facebook are as follows : <br /> Logging URL : http://destructible.me/l2l/users/login/ <br /> Username : %s <br /> Password : %s <br />" % (email,password)
					msg=EmailMessage('You have successfully regestered to L2L App with Facebook credentials.',emailmsg,settings.DEFAULT_FROM_EMAIL,[email])
					msg.content_subtype="html"
					msg.send()
					registration_status = 1
					
				except:
					registration_status = 0
				
				#auto- login for fb users
				email=request.session["fb_user_email"]
				user = User.objects.get(email = email,is_active=True)
				user.backend = 'django.contrib.auth.backends.ModelBackend'
				login(request,user)
				#redirect to his/her dashboard
				title="Registration Succeeded!!"
				message="You are successfully registered using Your Facebook Login.Please check Your email for your Login Credentials,Thank you."
				variables = RequestContext(request,{'title':title,'message':message,'user':user})
				#try:
				del request.session["fb_user_email"] 
				del request.session["fb_user_passsword"] 
				del request.session["fb_user"]
				#except KeyError:
					
				return render_to_response('/l2l/user/dashboard.html',variables)
							
			#except:
				#title="Registration Failed,couldnot save!!"
				#message="Try again!!"	
				#variables = RequestContext(request,{'form1': form1,'title':title,'message':message})
				#return render_to_response('user/fb_registration.html',variables)
		else:
			errs=form1.errors
			
			#form = RegistrationForm()
			variables = RequestContext(request,{'form1': form1,'message':errs})
			return render_to_response('/l2l/user/fb_registration.html',variables)	
	else:
		form1 =  UserProfileForm()
		variables = RequestContext(request,{'form1': form1,'message':'Continue Registration Using Facebook Login info'})
		return render_to_response('/l2l/user/fb_registration.html',variables)
		#return HttpResponse("Facebook registration successful")
	

def privacySettings(request):
	usr=userprofile.objects.get(user=request.user.id)
	#return HttpResponse(usr.visible_in_search)
	if request.method == 'POST':
		if usr.visible_in_search==True:
			usr.visible_in_search=False
			usr.save()
			return HttpResponse('You are now invisible in Search.')
		else:
			usr.visible_in_search=True
			usr.save()
			return HttpResponse('You are now visible in Search.')
	else:
		title="Privacy Settings"		
		variables=RequestContext(request,{'usr':usr,'title':title})
		return render_to_response('user/privacy_settings.html',variables)

@login_required
def accountSettings(request):
		usr,created_usr=userprofile.objects.get_or_create(user=request.user.id)
		ext=ExternalLink.objects.filter(user=usr.user)
		images = ImageGallery.objects.filter(user=request.user.id)
		len_images = len(list(images))
		variables=RequestContext(request,{'usr':usr,'ext':ext,'images':images,'len_images':len_images})
		return render_to_response('user/account_settings.html',variables)

@login_required
def myProfile(request):
    return render_to_response('user/myprofile.html', RequestContext(request,{}))

def viewProfile(request,user_profile_id):
    
    variables = {}
    
    try:
        matching_profile,created_profile = userprofile.objects.get_or_create(id=user_profile_id)
    except:
        matching_profile = None
        
    if not matching_profile:
        raise Http404
    
    profile_user = matching_profile.user
    
    usr_blogs = []
    ext = []
    member_firms = [] 
    if profile_user:
        usr_blogs=profile_user.personal_blogs.all()
        ext = profile_user.external_links.all()
        member_firms= getMemberFirmsOf(profile_user)
        
    showrequest=1
        
    if request.user.id:
        friend_obj=Friends.objects.filter(initiator=request.user,receiver=profile_user)
        f2=Friends.objects.filter(initiator=profile_user,receiver=request.user)
        if len(friend_obj)>0 or len(f2)>0:
        	showrequest=0
            	
	if matching_profile.user_type==2:
		school=getLawschoolByEmail(profile_user.email)
		#return HttpResponse(school)
		variables = RequestContext(request,{'school':school,'ext':ext,'member_firms':member_firms,'usr': matching_profile,'title':'View Profile'})
	else:			
		#r=Referrals.objects.filter(refered_to=refer_to_user)		
		#referrals_received=len(r)
		#r=Referrals.objects.filter(refered_by=refer_to_user)
		#referrals_sent=len(r)
		images = ImageGallery.objects.filter(user=profile_user)
		len_images = len(list(images))
		variables = RequestContext(request,{'showrequest':showrequest,'blogs':usr_blogs,'referrals_sent':0,'referrals_received':0,'ext':ext,'member_firms':member_firms,'usr': matching_profile,'title':'View Profile','images':images,'len_images':len_images})
    	#return render_to_response('user/view_profile.html',variables)
    return render_to_response('user/myprofile.html', variables)

@login_required
def deleteAccount(request):
	usr=User.objects.get(pk=request.user.id)
	usr.is_active=False	
	usr.save()
	username=usr.username
	first_name=usr.first_name
	last_name=usr.last_name
	email=usr.email
	logout(request)
	#send message to admin for confirmation and to delete account
	email=usr.email
	email_admin=getAdminEmail()
	addlink='%s%s%s%s%s%s%s%s'%('User ',username,' has Deleted his account.Please confirm the user account and Delete the user from admin panel.<br/>First Name : ',first_name,'<br/>Last Name : ',last_name,'<br/>Email : ',email)
	email_message=addlink
	msg=EmailMessage('L2L Account Delete Confirmation',email_message,email_admin,[email])
	msg.content_subtype="html"
	msg.send()
	title="Account Deleted"
	message="You Account has been deleted Successfully."
	variables = RequestContext(request,{'title':title,'messsage':message})
	return render_to_response('pages/success_page.html',variables)

@login_required
def addExternalLink(request):
	if request.method == 'POST':
		title=request.POST['title']
		link=request.POST['link']
		obj=ExternalLink()
		obj.title=title
		obj.link=link
		obj.user=request.user
		obj.save()
		#return viewProfile(request,request.user.id)
		return HttpResponse('Link Successfully Added.')
	else:
		variables = RequestContext(request,{'title':'Add External Links','message':'You can add links of your Private blogs or so..'})
		return render_to_response('user/add_external_link.html',variables)
		
@login_required
def checkPassword(request):
	oldpassword=request.POST['oldpassword']
	if request.user.check_password(oldpassword): 
		return HttpResponse("true") 
	else:
		return HttpResponse("false")

@login_required
def editUserProfile(request):
    
    cur_user=User.objects.get(pk=request.user.id)
    cur_profile,created=userprofile.objects.get_or_create(user=cur_user)
    ext=ExternalLink.objects.filter(user=request.user.id)
    
    form2 = RegistrationFormedit(instance=cur_user)
    form1 = UserProfiledit(initial={'state':'NY'},instance=cur_profile)
    
    images = []
    len_images = 0
    
    if request.method == 'POST':
        form2 = RegistrationFormedit(request.POST,instance=cur_user)
        form1= UserProfiledit(request.POST,instance=cur_profile)
        if form2.is_valid():
            form2.save()
            if form1.is_valid():
                form1.save()
                return HttpResponseRedirect('/l2l/users/view-profile/%s' % cur_profile.id)
                    
    variables = RequestContext(request,{'profile':cur_profile,'ext':ext,'form1': form1,'form2': form2,'title':'Your Profile','images':images,'len_images':len_images})
    return render_to_response('user/editprofile_attorney.html',variables)

'''
@login_required
def editUserProfile(request):
	a=User.objects.get(pk=request.user.id)
	print a.id
	b=userprofile.objects.get(user=a.id)
	print b
	ext=ExternalLink.objects.filter(user=request.user.id)
	print ext
	if b.user_type==1:
		if request.method == 'POST':
			form2 = RegistrationFormedit(request.POST,instance=a)
			print form2.errors
			form1= UserProfiledit(request.POST,instance=b)
			print form1.errors
			if form2.is_valid():
				#updating user info
				form2.save()
				if form1.is_valid():
					#updating user profile details in child-table
					f=form1.save()
					if 'profile_image' in request.FILES:				
						img = ImageGallery()
						img.image = request.FILES["profile_image"]
						img.profile_image = True
						img.user = request.user
						img.save()
						fullimgname = str(img.image)
						fullimgname = fullimgname.split('/')
						img.imgname = fullimgname[1]
						img.save()
						imageResize(str(img.image))
						if len(ImageGallery.objects.filter(user=request.user)) != 0:					
							ImageGallery.objects.filter(user=request.user).update(profile_image=False)	
						img.profile_image = True
						img.save()	
					
					form2 = RegistrationFormedit(instance=a)
					form1=UserProfiledit(instance=b)
					images = ImageGallery.objects.filter(user=request.user)
					len_images = len(list(images))
					variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'title':'Profile updated successfully','images':images,'len_images':len_images})
					return render_to_response('user/editprofile_attorney.html',variables)
				#return render_to_response('registration/success_page.html',{'message':'You are successfully registerd,Thank you'})
				else:
					errs=form1.errors
					form2 = RegistrationFormedit(instance=a)
					form1=UserProfiledit(instance=b)
					images = ImageGallery.objects.filter(user=request.user)
					len_images = len(list(images))
					variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'message':errs,'images':images,'len_images':len_images})
					return render_to_response('user/editprofile_attorney.html',variables)
					
			else:
				errs1=form1.errors
				errs2=form2.errors
				errs='%s%s'%(errs1,errs2)
				form2 = RegistrationFormedit(instance=a)
				form1=UserProfiledit(instance=b)
				images = ImageGallery.objects.filter(user=request.user)
				len_images = len(list(images))
				variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'message':errs,'images':images,'len_images':len_images})
				return render_to_response('user/editprofile_attorney.html',variables)
				
		else:
			
			form2 = RegistrationFormedit(instance=a)
			form1=UserProfiledit(instance=b)
			images = ImageGallery.objects.filter(user=request.user)
			len_images = len(list(images))
			variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'title':'Your Profile','images':images,'len_images':len_images})
			return render_to_response('user/editprofile_attorney.html',variables)
	else:
		if request.method == 'POST':
			form2 = RegistrationFormedit(request.POST,instance=a)
			form1= UserProfiledit(request.POST,instance=b)
			if form2.is_valid():			
				#updating user info
				form2.save()
				
				if form1.is_valid():
					#updating user profile details in child-table
					f=form1.save()
					
					if 'profile_image' in request.FILES:					
						img = ImageGallery()
						img.image = request.FILES["profile_image"]
						img.profile_image = True
						img.user = request.user
						img.save()
						fullimgname = str(img.image)
						fullimgname = fullimgname.split('/')
						img.imgname = fullimgname[1]
						img.save()
						imageResize(str(img.image))
						if len(ImageGallery.objects.filter(user=request.user)) != 0:					
							ImageGallery.objects.filter(user=request.user).update(profile_image=False)	
						img.profile_image = True
						img.save()	
					
					form2 = RegistrationFormedit(instance=a)
					form1=UserProfiledit(instance=b)
					images = ImageGallery.objects.filter(user=request.user)
					len_images = len(list(images))
					variables = RequestContext(request,{'form1': form1,'form2': form2,'title':'Profile updated successfully','images':images,'len_images':len_images})
					return render_to_response('user/editprofile_student.html',variables)
				#return render_to_response('registration/success_page.html',{'message':'You are successfully registerd,Thank you'})
				else:
					errs=form1.errors
					form2 = RegistrationFormedit(instance=a)
					form1=UserProfiledit(instance=b)
					images = ImageGallery.objects.filter(user=request.user)
					len_images = len(list(images))
					variables = RequestContext(request,{'form1': form1,'form2': form2,'message':errs,'images':images,'len_images':len_images})
					return render_to_response('user/editprofile_student.html',variables)
			else:
				errs1=form1.errors
				errs2=form2.errors
				errs='%s%s'%(errs1,errs2)
				form2 = RegistrationFormedit(instance=a)
				form1=UserProfiledit(instance=b)
				images = ImageGallery.objects.filter(user=request.user)
				len_images = len(list(images))
				variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'message':errs,'images':images,'len_images':len_images})
				return render_to_response('user/editprofile_student.html',variables)
				
		else:
			
			form2 = RegistrationFormedit(instance=a)
			form1=UserProfiledit(instance=b)
			images = ImageGallery.objects.filter(user=request.user)
			len_images = len(list(images))
			variables = RequestContext(request,{'form1': form1,'form2': form2,'title':'Your Profile','images':images,'len_images':len_images})
			return render_to_response('user/editprofile_student.html',variables)
'''

	
@login_required
def editUserProfile_old(request):
	a=User.objects.get(pk=request.user.id)
	b=userprofile.objects.get(user=a.id)
	ext=ExternalLink.objects.filter(user=request.user.id)
	if request.method == 'POST':
		form2 = RegistrationFormedit(request.POST, instance=a)
		form1= UserProfiledit(request.POST, instance=b)
		if form2.is_valid():			
			#updating user info
			form2.save()
			
			if form1.is_valid():
					#updating user profile details in child-table
					f=form1.save()				
					variables = RequestContext(request,{'title':'Profile Updated','message':'Your Profile has successfully been updated,Thank you'})
					return render_to_response('pages/success_page.html',variables)
				#return render_to_response('registration/success_page.html',{'message':'You are successfully registerd,Thank you'})
			else:
				errs=form1.errors
				form2 = RegistrationFormedit(instance=a)
				form1=UserProfiledit(instance=b)
				variables = RequestContext(request,{'form1': form1,'form2': form2,'message':errs})
				return render_to_response('user/editprofile_student.html',variables)
		else:
			errs1=form1.errors
			errs2=form2.errors
			errs='%s%s'%(errs1,errs2)
			form2 = RegistrationFormedit(instance=a)
			form1=UserProfiledit(instance=b)
			variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'message':errs})
			return render_to_response('user/editprofile.html',variables)
			
	else:
		
		form2 = RegistrationFormedit(instance=a)
		form1=UserProfiledit(instance=b)
		variables = RequestContext(request,{'ext':ext,'form1': form1,'form2': form2,'message':'Your Profile'})
		return render_to_response('user/editprofile.html',variables)
	
def inactive_user(request):
    variables = RequestContext(request,{'title':'Error!','message':'Your account is still inactive! You will be notified when you can login.'})
    return render_to_response('pages/inactive_user_page.html',variables)

    
def userLogin(request):
    if not request.user.is_authenticated():
        next_url = '/'
        if request.GET:
           try:
               next_url=request.GET['next']
               variables = RequestContext(request,{'next_url':next_url,'title':'User Login','message': 'Please Enter Correct Login information Below','user': request.user} )
               return render_to_response('user/login.html',variables)  
           except Exception,err:
               variables = RequestContext(request,{ 'title':'User Login','message': 'Please Enter Correct Login information Below','user': request.user} )
               return render_to_response('user/login.html',variables)
        elif request.POST:
            username = request.POST['username']
            password = request.POST['password']
            next_url = request.POST['next_url']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    variables = RequestContext(request,{ 'loginmessage': 'Successfully logged in' ,'user': request.user} )
                    if request.POST['next_url']:
                        return HttpResponseRedirect(request.POST['next_url'])
                    else:
                        return showDashboard(request)
                else:
                    variables = RequestContext(request,{'title':'User is not verified Yet,You cannot login until Admin  verifies your account!','message': 'Inactive Username!! Try Again..' ,'user': request.user} )
                    return HttpResponseRedirect('/l2l/users/login/inactive/')
            else:
                variables = RequestContext(request,{'next_url':next_url,'title':'Login Failed!','message': 'Invalid Username or Password !! Try Again..' ,'user': request.user} )
                return render_to_response('user/login.html',variables)

        else:
            variables = RequestContext(request,{'next_url':next_url,'title':'Login Failed!','message': 'Invalid Username or Password !! Try Again..' ,'user': request.user} )
            return render_to_response('user/login.html',variables)
    
    return showDashboard(request)

def userLogin_old(request):
    if not request.user.is_authenticated():
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
				if user.is_active:
					login(request, user)
					variables = RequestContext(request,{ 'loginmessage': 'Successfully logged in' ,'user': request.user} )
					#return HttpResponse(request.GET['next'])
					return showDashboard(request)
				else:
					variables = RequestContext(request,{'title':'User is not verified Yet,You cannot login until Admin  verifies your account!','message': 'Inactive Username!! Try Again..' ,'user': request.user} )
					return render_to_response('user/login.html',variables)	
                    
            else:
                variables = RequestContext(request,{'title':'Login Failed!','message': 'Invalid Username or Password !! Try Again..' ,'user': request.user} )
                return render_to_response('user/login.html',variables)
                #return HttpResponse(str('fail'))
        else:
            variables = RequestContext(request,{ 'title':'User Login','message': 'Please Enter Correct Login information Below','user': request.user} )
            return render_to_response('user/login.html',variables)    
    else:
        return showDashboard(request)   

def userLogout(request):
    logout(request)
    return HttpResponseRedirect('/l2l/')   
    #return HttpResponseRedirect('/')   
      
@login_required
def showDashboard(request):
    try:
        variables = RequestContext(request,{'title':'User Registration','message': request.session["message"]})
        del request.session["message"] 
    except KeyError:
        variables = RequestContext(request,{'message':'Welcome to L2L','user': request.user,'title':'Dashboard'} )
        
    up = None
    try:
        up = request.user.get_profile()
    except:
        up = userprofile()
        up.user = request.user
        up.save()
        
    #user_profile,created_profile=userprofile.objects.get_or_create(user=request.user)
    temp = "/l2l/users/view-profile/" + str(up.id)
    return HttpResponseRedirect(temp)

def user_forgotpwd(request):   
    if request.method == 'POST':    
        email_add = request.POST["email"]
        
        try:
			usr = User.objects.get(email=email_add)
			N=6
			password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))

			algo = 'sha1'
			salt = get_hexdigest( algo, str(random.random()), str(random.random()))[:5]
			hsh = get_hexdigest( algo, salt, password)
			newpassword = '%s$%s$%s' % ( algo, salt, hsh )
			usr.password = newpassword
			usr.save()
			emailmsg = "Hello, %s, Your new password for L2L is <br /> Password : %s" % (usr.username,password)
			msg=EmailMessage('Your New Password from (L2L)',emailmsg,'info@l2l.com',[usr.email])
			msg.content_subtype="html"
			msg.send(fail_silently=True)

			#variables = RequestContext(request,{'loginmessage':'Password sent to your email '})
			#return render_to_response('usermanagement/login.html',variables)
			#request.session["successmsg"] = "Password updated successfully and sent to your email"
			#return HttpResponseRedirect('/home')
			return HttpResponse('Your new temporary password has been emailed to you.')
            
        except ObjectDoesNotExist:
            variables = RequestContext(request,{'message':"Login Details doesn't match to any user"})
            return render_to_response('user/forgotpassword.html',variables)
        
    else:
        variables = RequestContext(request)
        return render_to_response('user/forgotpassword.html',variables) 
  
@login_required
def changePassword_withoutajax(request):
	#form = RegistrationForm(request.POST)
	if request.method == 'POST':
		a=User.objects.get(pk=request.user.id)
		b=userprofile.objects.get(user=a.id)
		oldpassword = request.POST['oldpassword']
		newpassword = request.POST['newpassword']
		cnewpassword = request.POST['cnewpassword']
		#user = authenticate(password=oldpassword)
		if a.check_password(oldpassword): 
			if newpassword == cnewpassword:
				#user = User.objects.create_user(username=a.username,password=request.POST['password1'],email=a.email)
				algo = 'sha1'
				salt = get_hexdigest( algo, str(random.random()), str(random.random()))[:5]
				hsh = get_hexdigest( algo, salt, newpassword)
				newpassword = '%s$%s$%s' % ( algo, salt, hsh )
				a.password = newpassword
				a.save()
				variables = RequestContext(request,{'title':'SUCCESS MESSAGE','message':"Password Updated Successfully!. Thank You."})
				return render_to_response('pages/success_page.html',variables)	
			else:
				variables = RequestContext(request,{'message':"Your Password and Confirmation Password doesn't match"})
				return render_to_response('user/change_password.html',variables)
		else:
			variables = RequestContext(request,{'title':'Err','message':"Your Existing Password doesn't match"})
			return render_to_response('user/change_password.html',variables)
		
	else:
		#form = UserPasswordedit()
		variables = RequestContext(request,{'title':'Edit Password','message':'Change Your Password,Make it secure!'})
		return render_to_response('user/change_password.html',variables)
	   

@login_required
def changePassword(request):
	#form = RegistrationForm(request.POST)
	if request.method == 'POST':
		a=User.objects.get(pk=request.user.id)
		b=userprofile.objects.get(user=a.id)
		oldpassword = request.POST['oldpassword']
		newpassword = request.POST['newpassword']
		cnewpassword = request.POST['cnewpassword']
		#user = authenticate(password=oldpassword)
		if a.check_password(oldpassword): 
			if newpassword == cnewpassword:
				#user = User.objects.create_user(username=a.username,password=request.POST['password1'],email=a.email)
				algo = 'sha1'
				salt = get_hexdigest( algo, str(random.random()), str(random.random()))[:5]
				hsh = get_hexdigest( algo, salt, newpassword)
				newpassword = '%s$%s$%s' % ( algo, salt, hsh )
				a.password = newpassword
				a.save()
				#variables = RequestContext(request,{'title':'SUCCESS MESSAGE','message':"Password Updated Successfully!. Thank You."})
				#return render_to_response('pages/success_page.html',variables)	
				return HttpResponse('Password Updated Successfully!.')
			else:
				#variables = RequestContext(request,{'message':"Your Password and Confirmation Password doesn't match"})
				#return render_to_response('user/change_password.html',variables)
				return HttpResponse("Your Password and Confirmation Password doesn't match")
		else:
			variables = RequestContext(request,{'title':'Err','message':"Your Existing Password doesn't match"})
			return render_to_response('user/change_password.html',variables)
		
	else:
		#form = UserPasswordedit()
		variables = RequestContext(request,{'title':'Edit Password','message':'Change Your Password,Make it secure!'})
		return render_to_response('user/change_password.html',variables)






#Membership Section
def paymentAccepted(request):
    usr=userprofile.objects.get(user=request.user.id)
    usr.membership='PREMIUM'
    usr.save()
    mem=Memberships()
    mem.user=request.user
    mem.save()
    #get back to Account-settings
    #return accountSettings(request)
    return HttpResponseRedirect('/l2l/users/account-settings/')

def abortMembership(request):
    return HttpResponse('sorry!payment aborted')

def premiumMembership(request):
    usr=userprofile.objects.get(user=request.user.id)
    membership_cost=9.99
    paypal = {
        'amount': membership_cost,
        'item_name': 'L2L Attorney Premium Membership',
        'item_number': request.user.id,
        
        # PayPal wants a unique invoice ID
        'invoice': str(uuid.uuid1()), 
        
        # It'll be a good idea to setup a SITE_DOMAIN inside settings
        # so you don't need to hardcode these values.
        #'return_url': settings.SITE_DOMAIN + reverse('return_url'),
        #'cancel_return': settings.SITE_DOMAIN + reverse('cancel_url'),
        
        'return_url': 'http://localhost:8000/users/payment-accepted/',
        'cancel_return': 'http://localhost:8000/users/abort-membership/',
    }
    form = PayPalPaymentsForm(initial=paypal)
    if settings.DEBUG:
        rendered_form = form.sandbox()
    else:
        rendered_form = form.render()
    return render_to_response('user/premium_membership.html', {
        'usr' : usr,
        'membership_cost':membership_cost,
        'title':'L2L Premium Membership',
        'form' : rendered_form,
    }, RequestContext(request))	   
	   
#Friends Section


def sendFriendRequest(request,receiver_id):
	usr=Friends()
	usr_receiver=User.objects.get(pk=receiver_id)
	usr.receiver=usr_receiver
	usr.initiator=request.user
	usr.status='PENDING'
	verification_code=getRamdomCode(9999999)
	usr.verification_code=verification_code
	try:
		f=Friends.objects.get(receiver=receiver_id,initiator=request.user)
	except:	
		try:
			usr.save()
			receiver_usr=User.objects.get(pk=receiver_id)
			email=receiver_usr.email
			#email='themaheshe1@gmail.com'
			addlink='%s%s%s'%('<a href="http://destructible.me/l2l/users/accept-friend/',usr.verification_code,'">Respond to Friend Request,click here.</a>')
			email_message='%s%s%s%s'%('You have Received a Friend Request From ',request.user.username,'.Please click link below to Accept the Request<br/>',addlink)
			#send_mail('L2L Friend Request',email_message, 'no-reply@lawyertolawyerny.com',[email], fail_silently=False)
			msg=EmailMessage('L2L Friend Request',email_message,'no-reply@lawyertolawyerny.com',[email])
			msg.content_subtype="html"
			msg.send()
			request.session["sendmail_msg"] = "Friend Request Successfully Sent."
		except:
			request.session["sendmail_msg"] = "Email couldn't be sent due to mailing problem."
	#variables = RequestContext(request,{'title':title,'message':message})
	#email_user=User.objects.get(pk=receiver_id)
	#email=email_user.email
	
	return userListing(request)
	#render_to_response('pages/success_page.html',variables)


@login_required
def getFriends(userid):
	usr=userid.user.id
	#usr=User.objects.get(pk=userid)
	f=Friends.objects.filter(initiator=usr,status='APPROVED')
	return f


@login_required
def acceptFriend(request,verification_code):
	#f=Friends.objects.get(verification_code=verification_code,receiver=request.user.id)
	f=Friends.objects.get(verification_code=verification_code)
	if f.status=='PENDING':
		f.status="APPROVED"
		f.save()
		frnd_accepted=Friends()
		#frnd_accepted.initiator=request.user
		usr=User.objects.get(pk=f.receiver.id)
		frnd_accepted.initiator=usr
		frnd_accepted.receiver=f.initiator
		frnd_accepted.status="APPROVED"
		frnd_accepted.save()
	notifications=Friends.objects.filter(receiver=request.user.id,status='PENDING')
	message="Friend Accepted"
	variables = RequestContext(request,{'notifications':notifications,'title':'Your Notifications','message':message})
	return render_to_response('user/notifications.html',variables)	
	
	
@login_required
def declineFriend(request,verification_code):	
	f=Friends.objects.get(verification_code=verification_code,receiver=request.user.id)	
	if f.status=='PENDING':
		f.status="NOTNOW"
		f.save()
	notifications=Friends.objects.filter(receiver=request.user.id,status='PENDING')	
	message="Friend Request not Accepted For Now"
	variables = RequestContext(request,{'notifications':notifications,'title':'Your Notifications','message':message})
	return render_to_response('user/notifications.html',variables)	

@login_required	
def viewNotifications(request):
	notifications=Friends.objects.filter(receiver=request.user.id,status='PENDING')
	query='%s%s%s'%('select b.* from jobsapp_jobs a,jobsapp_jobsapplications b where a.id=b.job_id and a.posted_by_id=',request.user.id,' and b.status=1')
	jobs_applications=JobsApplications.objects.raw(query)	
	received_r=Referral.objects.filter(refered=request.user.id,status="PENDING")
    	sent_r=Referral.objects.filter(refered_by=request.user.id)
	variables = RequestContext(request,{'referrals':received_r,'jobs_applications':jobs_applications,'notifications':notifications,'title':'Your Notifications'})
	#return HttpResponse(request.user.id)
	return render_to_response('user/notifications.html',variables)


@login_required	
def addToFavourite(request,friendid):
	usr=User.objects.get(pk=friendid)
	f=Friends.objects.get(initiator=request.user,receiver=usr)
	f.is_favourite=True
	f.save()
	title="Added Successfully"
	message="Friend successfully added to your favourite list."
	return viewMyFriends(request,message,title)
	

@login_required	
def viewMyFavourites(request,message="",title=""):
	frnd_list=Friends.objects.filter(initiator=request.user,status="APPROVED",is_favourite=True)
	paginator = Paginator(frnd_list, 15) # Show 15 Users per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		friends = paginator.page(page)
	except (EmptyPage, InvalidPage):
		friends = paginator.page(paginator.num_pages)
	totalfriends='%s%s'%('Total Favourites:',len(frnd_list))
	
	if not title:
		title="friends"
	if not message:
		message=totalfriends
	variables = RequestContext(request,{'friends':friends,'title':title,'message':message})	
	return render_to_response('user/favourites_list.html',variables)

@login_required	
def inviteFriends(request):
	if request.method=='POST':
		emailto=request.POST['emailaddress']
		#send invitation through email
		emailmsg = "Your Friend %s %s  has sent you an invitation to L2L.Click the link below to join.<br/><a href='http://destructible.me/l2l/'>Join L2L</a>" % (request.user.first_name,request.user.last_name)
		msg=EmailMessage('L2L Invitation',emailmsg,request.user.email,[emailto])
		msg.content_subtype="html"
		msg.send()
		return HttpResponse('Invitation send to the given Email-Addres.')
	else:
		title="Invite Friends"
		message=""
		variables = RequestContext(request,{'title':title,'message':message})	
		return render_to_response('user/send_invitation.html',variables)

@login_required	
def unFriend(request,friendID):
	usr=User.objects.get(pk=friendID)
	frnd=Friends.objects.get(initiator=request.user,receiver=usr)
	frnd.status="CANCELED"
	frnd.save()
	title="Friend Removed."
	message='%s%s'%(usr.username,' is removed from your friend list.')
	return viewMyFriends(request,message,title)

@login_required	
def viewMyFriends(request,message="",title=""):
	frnd_list=Friends.objects.filter(initiator=request.user,status="APPROVED")
	paginator = Paginator(frnd_list, 15) # Show 15 Users per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		friends = paginator.page(page)
	except (EmptyPage, InvalidPage):
		friends = paginator.page(paginator.num_pages)
	totalfriends='%s%s'%('Total Friends:',len(frnd_list))
	
	if not title:
		title="friends"
	if not message:
		message=totalfriends
	usr_images = ImageGallery.objects.filter(user=request.user)
	len_images = len(list(usr_images))
	images = ImageGallery.objects.all()
	imgId = []					
	imgId = [ x.user for x in images ]
	variables = RequestContext(request,{'friends':friends,'title':title,'message':message,'imgId':imgId,'len_images':len_images,'images':images})	
	return render_to_response('user/friends_list.html',variables)

@login_required	
def userListing(request):
	#usr=userprofile.objects.all()
	#user_list=User.objects.get(pk=303714)
	user_list = User.objects.filter(is_active=1).exclude(username="admin").exclude(username=request.user.username).order_by('first_name')
	
	#usr_ids=[x.id for x in user_lists]
	#user_list=userprofile.objects.filter(user__in=usr_ids)
	paginator = Paginator(user_list, 10) # Show 15 Users per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		users = paginator.page(page)
	except (EmptyPage, InvalidPage):
		users = paginator.page(paginator.num_pages)
	try:
		frnd_list=Friends.objects.filter(initiator=request.user)		
		f=[]
		if frnd_list:
			for ff in frnd_list:
				f.append(ff.receiver.id)
	except:
		f=[]
	usr_images = ImageGallery.objects.filter(user=request.user)
	len_images = len(list(usr_images))
	images = ImageGallery.objects.all()
	imgId = []					
	imgId = [ x.user for x in images ]
	try:
		variables = RequestContext(request,{'frnd_list':f,'users':users,'title':'Friends','message':'Add Friends!','sendmail_msg':request.session["sendmail_msg"],'imgId':imgId,'len_images':len_images,'images':images})
		del request.session["sendmail_msg"]
	except:
		variables = RequestContext(request,{'frnd_list':f,'users':users,'title':'Friends','message':'Add Friends!','imgId':imgId,'len_images':len_images,'images':images})	
	return render_to_response('user/friends_search.html',variables)

	
def uploadmore(request):
    if request.method == "POST":           
        img = ImageGallery()
        usr = ImageGallery.objects.filter(user=request.user)
        if len(list(usr)) == 0:
            img.profile_image = True
        else:
            img.profile_image = False
        img.image = request.FILES["pictures"]                        
        
        img.user = request.user                    
        img.save()
        fullimgname = str(img.image)
        fullimgname = fullimgname.split('/')
        img.imgname = fullimgname[1]
        img.save()
        imageResize(str(img.image))
        return HttpResponse("Photo uploaded successfully")
    else:
        variables = RequestContext(request)
        return render_to_response('user/uploadmore.html',variables)

def changeprofpic(request):
    if request.method == "POST":
        imgId = request.POST["imageId"]
        img = ImageGallery()
        ImageGallery.objects.filter(user=request.user).update(profile_image=False)
        image = ImageGallery.objects.get(pk=imgId)
        image.profile_image=True
        image.save()
        return HttpResponse("Profile picture updated")
    else:
        images = ImageGallery.objects.filter(user=request.user)
        len_images = len(list(images))       
        variables = RequestContext(request,{'images':images,'len_images':len_images})
        return render_to_response('user/gallery.html',variables)

def deleteprofpic(request):
    import os
    img = ImageGallery.objects.get(id=request.POST["imageId"]) 
    if img.profile_image == True:  
        return HttpResponse("false")
    else: 
        path = "%s/profileimages/%s"%(settings.MEDIA_ROOT,img.imgname)
        os.remove(path)
        path = "%s/profileimages/80x90_%s"%(settings.MEDIA_ROOT,img.imgname)
        os.remove(path)
        path = "%s/profileimages/107x120_%s"%(settings.MEDIA_ROOT,img.imgname)
        os.remove(path)
        img.delete()
        return HttpResponse("true")

def imageResize(imgname):
    try:
        from PIL import Image, ImageOps
    except ImportError:
        import Image
        import ImageOps
    img_path ='%s%s%s'%(settings.PROJECT_ROOT,'/uploads/',imgname)
    
    image = Image.open(img_path) 
    
    # ImageOps compatible mode
    if image.mode not in ("L", "RGB"):
        image = image.convert("RGB")
    
    # For the image of size 80x90
    
    imagefit = ImageOps.fit(image,(80,90), Image.ANTIALIAS)
    imgfullname = imgname.split('/')
    dest_img_path ='%s%s%s%s'%(settings.PROJECT_ROOT,'/uploads/profileimages/','80x90_',imgfullname[1])
    imagefit.save(dest_img_path, quality=75)  

    # For the image of size 107x120
    imagefit = ImageOps.fit(image,(107,120), Image.ANTIALIAS)
    imgfullname = imgname.split('/')
    dest_img_path ='%s%s%s%s'%(settings.PROJECT_ROOT,'/uploads/profileimages/','107x120_',imgfullname[1])
    imagefit.save(dest_img_path, quality=75) 	
	
#bookmarks section
#bookmarks and library are the same thing.
@login_required	
def listLibrary(request):
	title="My L2L Library"
	try:
		bookmrk=Bookmarks.objects.get(user=request.user.id)
		message="Bookmarks list."
		categories = [x.id for x in bookmrk.categories.all()]
		site_blogs = Blog.objects.filter(category__in=categories).order_by('?')[:5]
		variables = RequestContext(request,{'bookmrk':bookmrk,'title':title,'message':message,'site_blogs':site_blogs})	
	except:		
		message="No bookmarks added yet."
		variables = RequestContext(request,{'title':title,'message':message})	
	return render_to_response('user/library_list.html',variables)
	
def savePersonalBookmark(request,blog_id):
    b=PersonalBlog.objects.get(pk=blog_id)
    try:
    	bookmrk=Bookmarks.objects.get(user=request.user.id)
        blogs_ids=[ x.id for x in bookmrk.blog_personal.all() ] 
        if int(blog_id) in blogs_ids:    
            return HttpResponse('already in Your Library.')
        else:
            qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_blog_personal(bookmarks_id,personalblog_id) values (',bookmrk.id,',',blog_id,')')
    	    runquery(qry)
    except ObjectDoesNotExist:
    	bookmrk=Bookmarks()
    	bookmrk.user=request.user
    	bookmrk.save()
    	qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_blog_personal(bookmarks_id,personalblog_id) values (',bookmrk.id,',',blog_id,')')
        runquery(qry)
    return HttpResponse('Personal Blog Bookmarked Successfully.')
	
def saveSiteBookmark(request,blog_id):
    b=Blog.objects.get(pk=blog_id)
    try:
        bookmrk=Bookmarks.objects.get(user=request.user.id)
        blogs_ids=[ x.id for x in bookmrk.blog_site.all() ] 
        if int(blog_id) in blogs_ids:    
            return HttpResponse('already in Your Library.')
        else:
              qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_blog_site(bookmarks_id,blog_id) values (',bookmrk.id,',',blog_id,')')
              runquery(qry)
    except ObjectDoesNotExist:
        bookmrk=Bookmarks()
        bookmrk.user=request.user
        bookmrk.save()
        qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_blog_site(bookmarks_id,blog_id) values (',bookmrk.id,',',blog_id,')')
        runquery(qry)
    return HttpResponse('Legal Blog Bookmarked Successfully.')
	
def saveCategoryBookmark(request,cat_id):
	#return HttpResponse(request.user.id)
    c=Category.objects.get(pk=cat_id)
    try:
        bookmrk=Bookmarks.objects.get(user=request.user.id)
        #return HttpResponse(any(cat_id in x.id for x in bookmrk.categories.all()))
        cat_ids=[ x.id for x in bookmrk.categories.all() ] 
        if int(cat_id) in cat_ids:    
            return HttpResponse('already in Your Library.')
        else:
            #return HttpResponse(cat_ids)
            qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_categories(bookmarks_id,category_id) values (',bookmrk.id,',',cat_id,')')
            runquery(qry)
    except ObjectDoesNotExist:
    	bookmrk=Bookmarks()
    	bookmrk.user=request.user
    	bookmrk.save()
    	qry='%s%s%s%s%s'%('insert into usermanagement_bookmarks_categories(bookmarks_id,category_id) values (',bookmrk.id,',',cat_id,')')
    	runquery(qry)
    return HttpResponse('Category Bookmarked Successfully.')
